package com.atguigu.tingshu.common.lock;

import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/*
    封装获取锁释放锁的逻辑
 */
public class GuiguLockUtil {
//    @Autowired
//    RedissonClient redissonClient;

    //获取锁的方法
    @SneakyThrows
    public static void lock(RedissonClient redissonClient,
                            String lockKey,long lockExpireTime , int lockRandomTime){
        //1、获取锁对象
        RLock lock = redissonClient.getLock(lockKey);
        //2、尝试获取锁
        boolean b = lock.tryLock(lockExpireTime, TimeUnit.SECONDS);
        if(!b){
            //4、获取失败自旋获取锁
            Thread.sleep(100+new Random().nextInt(lockRandomTime));
            lock(redissonClient,lockKey,lockExpireTime,lockRandomTime);
        }
        //3、获取成功结束
    }
    //释放锁的方法
    public static void unlock(RedissonClient redissonClient,
                              String lockKey){
        //1、获取锁对象
        RLock lock = redissonClient.getLock(lockKey);
        //释放锁: 如果当前线程持有锁 才释放锁
        if(lock.isLocked()){
            lock.unlock();
        }
    }
}
